package user

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/app/business/api/internal/repository/user"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzusersurvey"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"
	"unicode/utf8"

	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserSurveyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUserSurveyListLogic - 用户问卷列表
func NewUserSurveyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSurveyListLogic {
	return &UserSurveyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserSurveyListLogic) UserSurveyList(req *types.UserSurveyListRequest) (resp *types.UserSurveyListResponse, err error) {
	// 创建实例
	userSurveyDao := user.NewUserSurveyDao(l.ctx, l.svcCtx)

	// 获取用户问卷信息
	userSurveyConditions := make([]predicate.HzUserSurvey, 0)
	userSurveyConditions = append(userSurveyConditions, hzusersurvey.DeleteAtIsNil())
	userSurveyConditions = append(userSurveyConditions, hzusersurvey.UserSurveyTypeEQ(req.UserSurveyType))
	userSurveyList, err := userSurveyDao.UserSurveyConditionsAll(userSurveyConditions, 20)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户问卷信息失败：%v", err.Error()))
	}

	// 组装数据
	list := lo.Map(userSurveyList, func(item *ent.HzUserSurvey, _ int) *types.UserSurveyInfo {
		// 脱敏(取出字符串的第一个字符,固定拼接两个*）
		firstRune, _ := utf8.DecodeRuneInString(item.UserSurveyName)
		firstChar := string(firstRune)

		return &types.UserSurveyInfo{
			UserSurveyName:    firstChar + "*" + "*",
			UserSurveyOrderAt: time.Unix(item.CreatedAt, 0).Format(time.DateTime),
		}
	})

	//返回数据
	resp = &types.UserSurveyListResponse{
		List: list,
	}

	return
}
